const rabbitMQ = require('./index');
const { createFriend, getFriendList } = require('../model/chatList');
const { createMsg } = require('../model/msg');
const socketWrapper = require('../socketio');
const { redisGet, redisSet } = require('../utils/redis');
const { SensitiveWord } = require('../model/sensitiveWord');

const SENSITIVE_WORDS_KEY = 'mim-sensitive-words';

// 检查消息中的敏感词
async function checkSensitiveWords(content) {
    try {
        // 从Redis获取敏感词列表
        const sensitiveWords = await redisGet(SENSITIVE_WORDS_KEY) || {};
        const triggeredWords = [];

        // 检查每个敏感词
        for (const word in sensitiveWords) {
            if (sensitiveWords[word].status === 0 && content.includes(word)) {
                triggeredWords.push(sensitiveWords[word]);
            }
        }

        // 更新触发次数
        for (const word of triggeredWords) {
            await SensitiveWord.findByIdAndUpdate(
                word._id,
                { $inc: { triggerCount: 1 } }
            );
        }

        return triggeredWords;
    } catch (error) {
        console.error('检查敏感词失败:', error);
        return [];
    }
}

// 生产者
async function sendNotification(msg) {
    await rabbitMQ.publish('imChatMsg', msg);
}

// 消费者
async function startNotificationConsumer() {
    await rabbitMQ.consume('imChatMsg', async (message) => {
        try {
            await processNotification(message);
        } catch (error) {
            console.error('通知处理失败:', error);
            // 错误处理逻辑
        }
    });
}

// 处理消息
async function processNotification(message) {
    console.log('message MQ', message)
    try {
        // 检查消息内容中的敏感词
        if (message.content) {
            const triggeredWords = await checkSensitiveWords(message.content);
            if (triggeredWords.length > 0) {
                console.log('触发敏感词:', triggeredWords.map(w => w.word).join(', '));
            }
        }
        const msgData = {
            user: message.from,
            toUser: message.to,
            msg: message
        }
        if (message.msgKey) msgData.msgKey = message.msgKey;
        // 计算和更新3分钟内回复率
        if (message.toType != 3 && message.fromType != 3) { // 排除和客服的对话，不需要统计回复率
            const latestMsg = await getLatestMsg(message.from, message.to);
            if (latestMsg) {
                const nowTime = Date.now(); // 当前时间
                const threeMinutes = 3 * 60 * 1000; // 3分钟
                const friendList = await getFriendList(message.from); // 当前用户好友列表
                const friendLength = friendList.length; // 总好友数量
                const userInfo = await redisGet(`mim-${message.from}`); // 当前用户信息
                if (userInfo) {
                    // 获取当前回复率，如果没有则默认为0
                    const currentResponseRate = userInfo.responseRate || 0;
                    let newResponseRate;

                    if (friendLength === 0) {
                        newResponseRate = 100;
                    } else {
                        // 计算每次回复对回复率的影响值
                        const impactValue = 100 / friendLength;

                        if (nowTime - latestMsg < threeMinutes) {
                            // 3分钟内回复，提高回复率
                            newResponseRate = Math.min(100, currentResponseRate + impactValue);
                        } else {
                            // 超过3分钟回复，降低回复率
                            newResponseRate = Math.max(0, currentResponseRate - impactValue);
                        }
                    }

                    // 更新用户信息中的回复率
                    userInfo.responseRate = newResponseRate;
                    await redisSet(`mim-${message.from}`, userInfo);
                }
            }
        }
        const saveMsg = await createMsg(msgData);
        if (message.toType != 3 && message.fromType != 3) { // 类型1得加好友，其他比如客服，只添加到对方好友列表不添加到自己好友列表
            const saveChatList1 = await createFriend({
                user: message.from,
                toUser: message.to,
                lastMessage: message
            });
            const saveChatList2 = await createFriend({
                user: message.to,
                toUser: message.from,
                lastMessage: message
            });
            console.log(3)
        } else { // 是客服对话
            if (message.toType === 3) {
                console.log(1)
                await createFriend({
                    user: message.to,
                    toUser: message.from,
                    lastMessage: message
                });
            }
            if (message.fromType === 3) {
                console.log(2)
                await createFriend({
                    user: message.from,
                    toUser: message.to,
                    lastMessage: message
                });
            }
        }
        const toUserInfo = await redisGet(`mim-${message.to}`);
        if (toUserInfo.socketId && toUserInfo.online === 1) {
            const socket = socketWrapper.getIO();
            msgData.id = String(saveMsg._id);
            if (message.fromType === 3) {
                const serviceInfo = await redisGet('mim-IMservice')
                if (serviceInfo) {
                    serviceId = serviceInfo.imKey
                    msgData.user = serviceId
                    msgData.msg.from = serviceId
                }
            }
            socket.to(toUserInfo.socketId).emit('chatMsg', {
                code: 200,
                data: msgData
            });
        }
        return Promise.resolve(true);
    } catch (e) {
        console.log('processNotification error', e.message)
    }
}

module.exports = {
    sendNotification,
    startNotificationConsumer
};